package com.javasm.commons.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.javasm.commons.entity.CrmProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Component
public class OssUtil implements InitializingBean {
    private static OSS ossClient =null;
    @Resource
    private CrmProperties cp;
    @Override
    public void afterPropertiesSet() throws Exception {
        CrmProperties.Oss oss = cp.getOss();
        ossClient = new OSSClientBuilder().build(oss.getEndpoint(), oss.getAccessKeyId(), oss.getAccessKeySecret());
    }

    public static String uploadFile(String bucketName,String objectName,InputStream inputStream){
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            putObjectRequest.setProcess("true");
            ossClient.putObject(putObjectRequest);
        } catch (Exception oe) {
            throw oe;
        }
        return objectName;
    }

    //系统中上传图片,一般需要回显预览图片,需要返回一个图片的网络路径http://域名/
    public static String getUrl(String bucketName,String objectName){
        Date expiration = new Date(new Date().getTime() + 1000 * 60*60*24*365*100L);
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
        req.setExpiration(expiration);
        URL signedUrl = ossClient.generatePresignedUrl(req);
        return signedUrl.toString();
    }

    public static InputStream download(String bucketName,String objectName) throws IOException {
        InputStream in = null;
        try {
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            in = ossObject.getObjectContent();
//            ossObject.close();
        }catch (Exception e){
            throw e;
        }
        return in;
    }

    public static void del(String bucketName,String objectName){
        try {
            ossClient.deleteObject(bucketName, objectName);
        } catch (Exception oe) {
           throw oe;
        }
    }

    @PreDestroy
    public void shutdown(){
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

}
